package com.shujia.spark.stream

import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.streaming.dstream.{DStream, InputDStream}
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe

object Demo7Kafka {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()

    conf.setAppName("kafka")
    conf.setMaster("local[2]")


    val sc = new SparkContext(conf)

    val ssc = new StreamingContext(sc, Durations.seconds(5))

    ssc.checkpoint("data/checkpoint")

    /**
      * 通过spark streaming消费kafka中的数据
      *
      */

    val kafkaParams: Map[String, Object] = Map[String, Object](
      ///kafka集群列表
      "bootstrap.servers" -> "master:9092,node1:9092,node2:9092",
      //key value的反序列化的类
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      //消费者组
      "group.id" -> "asdasdasd",
      //读取数据的位置 latest: 读取最新的数据， earliest：读取所有的数据
      "auto.offset.reset" -> "earliest",
      //是否开启自动提交消费便宜量，消费便宜量默认保存至zookeeper
      "enable.auto.commit" -> "true"
    )

    val topics = Array("words")

    //基于kafka创建DStream
    val kafkaDStream: InputDStream[ConsumerRecord[String, String]] = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topics, kafkaParams)
    )

    //取出数据
    val linesDS: DStream[String] = kafkaDStream.map(record => record.value())

    val wordsDS: DStream[String] = linesDS.flatMap(_.split(","))

    val kvDS: DStream[(String, Int)] = wordsDS.map((_, 1))

    //累加统计单词的数量
    val countDS: DStream[(String, Int)] = kvDS.updateStateByKey((seq: Seq[Int], option: Option[Int]) => Option(seq.sum + option.getOrElse(0)))


    countDS.print()


    ssc.start()
    ssc.awaitTermination()
    ssc.stop()

  }

}
